// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

const db = cloud.database();
// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  try {
    //通过JS的方法获取当前年月日
    var date = new Date();
    date = new Date(date.getTime() + 8 * 60 * 60 * 1000);
    //获取年份  
    const Y = date.getFullYear();
    //获取月份  
    const M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
    //获取当日日期 
    const D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
    var today = await db.collection('learnDays').where({
      user_id: wxContext.OPENID,
      time: {
        year: Y,
        month: M,
        day: D,
      }
    }).get();

    var yes = null;
    var learnDays = today.data[0] == null ? 0 : 1;
    while (true) {
      date = new Date(date.setTime(date.getTime() - 24 * 60 * 60 * 1000));
      //获取昨天?年份  
      yes_Y = date.getFullYear();
      //获取昨天?月份  
      yes_M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
      //获取昨天?日期 
      yes_D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
      yes = await db.collection('learnDays').where({ //yes：昨天的数据
        user_id: wxContext.OPENID,
        time: {
          year: yes_Y,
          month: yes_M,
          day: yes_D,
        }
      }).get();
      if (yes.data[0] == null) break;
      learnDays++;
    }

    /////////////////////////////////////////////////////
    var today = await db.collection('reviewDays').where({
      user_id: wxContext.OPENID,
      time: {
        year: Y,
        month: M,
        day: D,
      }
    }).get();

    var date = new Date();
    date = new Date(date.getTime() + 8 * 60 * 60 * 1000);
    var reviewDays = today.data[0] == null ? 0 : 1;
    while (true) {
      date = new Date(date.setTime(date.getTime() - 24 * 60 * 60 * 1000));
      //获取昨天?年份  
      yes_Y = date.getFullYear();
      //获取昨天?月份  
      yes_M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
      //获取昨天?日期 
      yes_D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
      yes = await db.collection('reviewDays').where({ //yes：昨天的数据
        user_id: wxContext.OPENID,
        time: {
          year: yes_Y,
          month: yes_M,
          day: yes_D,
        }
      }).get();
      if (yes.data[0] == null) break;
      reviewDays++;
    }
    return {
      learnDays: learnDays,
      reviewDays: reviewDays
    }

  } catch (e) {
    console.error(e);
  }
}